﻿using Lee.EF.Context;
using Lee.Models.Entities;
using Microsoft.EntityFrameworkCore;

namespace EFCoreApp;

/// <summary>
/// 悲观并发控制
/// </summary>
public class EF_updlock
{
    public void uplockTest()
    {
        string _currOwner = "test";//Console.ReadLine();//当前用户
        using var ctx = new MyDBContext();
        using var tx = ctx.Database.BeginTransaction();
        FormattableString sql = $@"select * from Coupons with(updlock) where id=2";
        var cop = ctx.Set<Biz_Coupons>().FromSqlInterpolated(sql).Single();//FromSqlInterpolated
        if (!string.IsNullOrEmpty(cop.Owner))
        {
            Console.WriteLine($"券被抢了");
        }
        else
        {
            cop.Owner = _currOwner;
            Thread.Sleep(5000);
            ctx.SaveChanges();
            Console.WriteLine($"恭喜{_currOwner}抢到券{cop.Id}了");
        }
        tx.Commit();
        Console.WriteLine($"EF_updlock end");
    }
}